package redpacket.mq;

import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import redpacket.mapper.RedPacketMapper;
import redpacket.mapper.RedPacketRecordMapper;
import redpacket.model.RedPacket;
import redpacket.model.RedPacketRecord;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class GrabConsumer {

    private final RedPacketRecordMapper recordMapper;
    private final RedPacketMapper redPacketMapper;

    @RabbitListener(queues = "rp.grab.queue")
    public void onMessage(Map<String, Object> payload) {
        Long packetId = Long.valueOf(payload.get("packetId").toString());
        Long userId = Long.valueOf(payload.get("userId").toString());
        BigDecimal amount = new BigDecimal(payload.get("amount").toString());

        RedPacketRecord r = new RedPacketRecord();
        r.setPacketId(packetId);
        r.setUserId(userId);
        r.setAmount(amount);
        r.setCreateTime(LocalDateTime.now());
        recordMapper.insert(r);

        // decrease remain_count; if 0 then mark finished
        RedPacket rp = redPacketMapper.findById(packetId);
        if (rp != null && rp.getRemainCount() != null && rp.getRemainCount() > 0) {
            int remain = rp.getRemainCount() - 1;
            rp.setRemainCount(remain);
            if (remain == 0) rp.setStatus(2);
            redPacketMapper.updateRemainAndStatus(rp);
        }
    }
}
